import {ElLoading, ElMessage, ElMessageBox} from 'element-plus'
import axios from 'axios'
import router from "@/router";
import {useRoute} from "vue-router";
const TOKEN_NAME = 'token'

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        let token = localStorage.getItem(TOKEN_NAME)
        if (token) {
            config.headers[TOKEN_NAME] = token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.code === 200) {
            return res
        }
        if (res.code === 401) {
            ElMessageBox.alert('登录过期，请重新登录~', '提示', {
                type: 'warning',
                showClose: false,
                confirmButtonText: '确定'
            }).then(() => {
                localStorage.clear()
                window.location.reload()
            })
        }else if(res.code === 410){
            ElMessageBox.alert(res.msg, {
                type: 'warning',
                showClose: false,
                confirmButtonText: '确定'
            }).then(() => {

                router.push('/center')
            })


        } else {
            ElMessage({
                type: 'error',
                message: res.msg,
                duration: 4 * 1000
            })
        }
        return Promise.reject(new Error(res.msg || 'Error'))
    },
    error => {
        ElMessage({
            type: 'error',
            message: error.message || 'Error',
            duration: 4 * 1000
        })
        return Promise.reject(error)
    }
)





export default service
